package poc;

import org.docx4j.TextUtils;
import org.docx4j.XmlUtils;
import org.docx4j.toc.TocHelper;
import org.docx4j.wml.P;
import org.docx4j.wml.R;
import poc.myrun.MyRun;
import poc.server.Server;
import poc.utils.RunUtil;
import poc.utils.StringUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by zhangleilei on 2018/10/11.
 */
public class Paragraph {
    public static void trans(P p){
        String chineseSnippet= TextUtils.getText(p);
        if (!Server.getInstance().needTrans(chineseSnippet)){
            return;
        }
        List<Object> runs = TocHelper.getAllElementsFromObject(p, R.class);
        if (runs.size()==0){
            return;
        }

        String engSnippet=Server.getInstance().getParagraphEng(chineseSnippet);
        R defaultRun=(R)RunUtil.findDefaultRunInParagraph(runs);
        List<MyRun> myRunList = RunUtil.findMyRunList(chineseSnippet,runs,defaultRun);
        List<String> cValues=new ArrayList<String>();
        for (int index=0;index<myRunList.size();index++){
            cValues.add(myRunList.get(index).cValue);
        }
        Map<String,String> eValueMap=Server.getInstance().getListTransMap(cValues);
        p.getContent().clear();
        parserParagraph(engSnippet,eValueMap,myRunList,p,defaultRun);
    }

    private static void parserParagraph(String engSnippet,Map<String,String> eValueMap,List<MyRun> myRunList,P p,R defaultRun){
        if (eValueMap.size()>0){
            for (MyRun myRun:myRunList){
                String eValue=eValueMap.get(myRun.cValue);
                if (myRun.find(engSnippet,eValue)){
                    String leftStr=myRun.getLeftStr(engSnippet,eValue);
                    String rightStr=myRun.getRightStr(engSnippet,eValue);

                    if (!StringUtil.isEmpty(leftStr)){
                        parserParagraph(leftStr,eValueMap,myRunList,p,defaultRun);
                    }
                    myRun.addRun(p,eValue);
                    if (!StringUtil.isEmpty(rightStr)){
                        parserParagraph(rightStr,eValueMap,myRunList,p,defaultRun);
                    }
                    return;
                }
            }
        }
        R run= XmlUtils.deepCopy(defaultRun);
        RunUtil.setRunText(run,engSnippet);
        p.getContent().add(run);
    }
}
